package com.test.resumeanalysis

import android.content.Intent
import android.os.Bundle

import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.findNavController
import com.setruth.mvvmbaseproject.network.ApiResponse
import com.setruth.mvvmbaseproject.network.api.ResumeParseApi
import com.test.resumeanalysis.common.BaseVBActivity
import com.test.resumeanalysis.data.DataBase

import com.test.resumeanalysis.data.model.ResumeRequestBean

import com.test.resumeanalysis.databinding.ActivityMainBinding
import com.test.resumeanalysis.util.FileUtil
import com.test.resumeanalysis.util.LogUtil

import com.test.resumeanalysis.view.ResumePopupWindow
import com.test.resumeanalysis.viewModel.PublicViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : BaseVBActivity<ActivityMainBinding>(ActivityMainBinding::inflate) {

    companion object {
        const val PICK_PHOTO = 100001
        const val PICK_FILE = 100002
    }


    private val model: PublicViewModel by viewModels()
    private lateinit var navController: NavController


    override fun onInit(savedInstanceState: Bundle?) {

        val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.nav_host_fragment_container) as NavHostFragment
        navController = navHostFragment.findNavController()


        binding.navMain.setOnItemSelectedListener {
            if (it.isChecked) {
                return@setOnItemSelectedListener true
            }
            when (it.itemId) {
                R.id.menu_home -> {
                    navController.navigate(R.id.menu_home)
                }
                R.id.menu_talent -> {
                    navController.navigate(R.id.menu_talent)
                }
                R.id.menu_resume -> {

                    val mPopupWindow =
                        ResumePopupWindow(this, object : ResumePopupWindow.OnClickListener {
                            override fun picOnClick() {
                                openAlbum()
                            }

                            override fun pdfOnClick() {
                                pickFile()
                            }

                            override fun cancel() {
                            }
                        })
                    mPopupWindow.setDialogMessage("");
                    mPopupWindow.show(binding.root);
                    return@setOnItemSelectedListener false
                }

            }
            true
        }

        navController.addOnDestinationChangedListener { _, destination, _ ->
            when (destination.id) {
                R.id.menu_home, R.id.menu_talent -> {
                    showBottomNav()
                }
                R.id.menu_resume -> {
                    showBottomNav()
                }
                else -> {
                    hideBottomNav()
                }
            }
        }

    }


    /**
     * BottomNav显示控制
     */
    private var isShowBottomNav = true

    /**
     * 显示导航
     */
    private fun showBottomNav() {
        if (!isShowBottomNav) {
            binding.navMain.visibility = View.VISIBLE
            isShowBottomNav = true
        }
    }

    /**
     * 隐藏导航
     */
    private fun hideBottomNav() {
        if (isShowBottomNav) {
            binding.navMain.visibility = View.GONE
            isShowBottomNav = false
        }
    }


    private fun openAlbum() {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = "android.intent.action.GET_CONTENT"
        intent.addCategory("android.intent.category.OPENABLE")
        startActivityForResult(intent, PICK_PHOTO)
    }


    private fun pickFile() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        startActivityForResult(intent, PICK_FILE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                PICK_PHOTO ->
                    data?.data?.let { uri ->

                        val realPath = FileUtil.getFileRealPath(this@MainActivity, uri)
                        realPath?.let {
                            GlobalScope.launch {
                                withContext(Dispatchers.IO) {
                                    val filePath = it
                                    val resumeRequestBean = FileUtil.filetoBase64(filePath)
                                    postResumeRequest(resumeRequestBean)
                                }
                            }
                        }
                    }
                PICK_FILE -> {
                    data?.data?.let { uri ->
                        uri.apply {
                            val realPath = FileUtil.getFileRealPath(this@MainActivity, uri)
                            realPath?.let {
                                GlobalScope.launch {
                                    withContext(Dispatchers.IO) {
                                        val filePath = it
                                        val resumeRequestBean = FileUtil.filetoBase64(filePath)
                                        postResumeRequest(resumeRequestBean)
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
    }


    private fun postResumeRequest(resumeRequestBean: ResumeRequestBean) {
        model.apply {
            request(ResumeParseApi::class.java).Parse(resumeRequestBean = resumeRequestBean)
                .getResponse {
                    it.collect {
                        when (it) {
                            is ApiResponse.Error -> LogUtil.e("${it.errMsg} ${it.exception}")
                            ApiResponse.Loading -> LogUtil.e("Loading")
                            is ApiResponse.Success -> {
                                val data = it?.data
                                data?.let {
                                    DataBase.getDataBase(this@MainActivity)
                                    val dao =
                                        DataBase.getDataBase(this@MainActivity).resumeDao()
                                    dao.insertData(data)
                                }
                                withContext(Dispatchers.Main){
                                    Toast.makeText(this@MainActivity,"成功录入该简历",Toast.LENGTH_LONG).show()
                                    binding.navMain.selectedItemId=R.id.menu_talent
                                    navController.navigate(R.id.menu_talent)
                                }

                            }
                        }
                    }
                }
        }
    }

}